package org.bank;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.bank.dao.AccountDAO;
import org.bank.dto.AccountTO;

/**
 * Session Bean implementation class BankBean
 */
@Stateless
public class BankBean implements Bank {

	@EJB
	private AccountDAO accountDAO;

	/**
	 * Default constructor.
	 */
	public BankBean() {
	}

	@Override
	public boolean createAccount(AccountTO accountTO) {
		return accountDAO.createAccount(accountTO);
	}

	@Override
	public AccountTO getAccount(int accountNumber) {
		// TODO Auto-generated method stub
		return accountDAO.findAccount(accountNumber);
	}

	@Override
	public boolean editAccount(int accountNumber, String firstName,
			String lastName, String address, String phoneNumber) {
		// TODO Auto-generated method stub
		//Editing only the fields related to the person owning the account, not the balance.
		AccountTO accountTO = accountDAO.findAccount(accountNumber);
		accountTO.address = address;
		accountTO.firstName = firstName;
		accountTO.phone = phoneNumber;
		accountTO.lastName = lastName;
		return accountDAO.updateAccount(accountTO);
	}

	@Override
	public int transferMoney(int accountNumber1, int accountNumber2,
			double amount) {
		AccountTO account1 = null;
		try {
			account1 = accountDAO.findAccount(accountNumber1);
		} catch (Exception ex) {
			return 1;// meaning that the first account number does not exist
		}
		AccountTO account2 = null;
		try {
			account2 = accountDAO.findAccount(accountNumber2);
		} catch (Exception ex) {
			return 2;// meaning that the second account number does not exist
		}
		if (amount <= account1.balance) {
			accountDAO.setBalance(accountNumber1, account1.balance - amount);
			accountDAO.setBalance(accountNumber2, account2.balance + amount);
			return 0; // meaning everything went ok
		} else
			return 3; // meaning amount is too big
	}

	@Override
	public boolean depositMoney(int accountNumber, double amount) {
		AccountTO account = null;
		try {
			account = accountDAO.findAccount(accountNumber);
		} catch (Exception ex) {
			return false;
		}
		accountDAO.setBalance(accountNumber, account.balance + amount);
		return true;
	}

	@Override
	public boolean withdrawMoney(int accountNumber, double amount) {
		AccountTO account = null;
		try {
			account = accountDAO.findAccount(accountNumber);
		} catch (Exception ex) {
			return false;
		}
		if (amount <= account.balance) {
			accountDAO.setBalance(accountNumber, account.balance - amount);
			return true;
		} else {
			return false;
		}
	}

}
